import axios, {
  AxiosInstance,
  AxiosResponse,
  AxiosRequestConfig,
  AxiosError
} from 'axios';
class HttpClient {
  public readonly instance: AxiosInstance
  public constructor() {
      this.instance = axios.create({
        timeout: 1000 * 30, // 请求超时时间30秒(单位:毫秒)
        headers: {
          "Content-Type": "application/json"
        },
        baseURL: "http://localhost:8080/"
      })
      // 1. 请求拦截器
      this._interceptorsRequest()
      // 2. 响应拦截器
      this._interceptorResponse()
  }
  private _interceptorsRequest = () => {
      this.instance.interceptors.request.use(
          this._handleRequest,
          this._handleRequestError
      )
  }
  private _handleRequest = (config: AxiosRequestConfig) => {
    return config;
  }
 private _handleRequestError(error: AxiosError) {
  return Promise.resolve({
    code: 1,
    msg: error.message || "请求失败"
  });
 }
  private _interceptorResponse = () => {
      this.instance.interceptors.response.use(
          this._handleResponse,
          this._handleResponeError
      )
  }
  private _handleResponse = (response: AxiosResponse) => {
    return response.data;
  }
  protected _handleResponeError = (error: AxiosError) => {
    const message: string = error.message || "";
    let msg = "";
    if (message.includes("timeout")) {
      msg = "请求超时，请刷新后重试";
    } else if (message.includes("Network Error")) {
      msg = "网络连接错误,请刷新后重试！";
    }
    return Promise.resolve({
      code: 1,
      msg: msg || message || "请求失败"
    });
  }
}
export default new HttpClient().instance;
